package com.sys.config;

import com.sys.common.JacksonObjectMapper;
import org.springframework.context.annotation.Configuration;
import org.springframework.http.converter.HttpMessageConverter;
import org.springframework.http.converter.json.MappingJackson2HttpMessageConverter;
import org.springframework.web.servlet.config.annotation.CorsRegistry;
import org.springframework.web.servlet.config.annotation.WebMvcConfigurer;

import java.util.List;

@Configuration
public class WebConfig implements WebMvcConfigurer {
    @Override
    public void addCorsMappings(CorsRegistry registry) {
        registry.addMapping("/**")
                //是否发送Cookie
                .allowCredentials(true)
                //放行哪些原始域
                .allowedOriginPatterns("*")
                .allowedMethods("GET", "POST", "PUT", "DELETE")
                .allowedHeaders("*")
                .exposedHeaders("*")
                .maxAge(60);    // 单位 s。当前跨域请求最大有效时间
    }

    @Override
    public void extendMessageConverters(List<HttpMessageConverter<?>> converters) {
        // 1. 创建消息转换器对象
        MappingJackson2HttpMessageConverter messageConverter = new MappingJackson2HttpMessageConverter();
        // 2. 设置对象转换器
        messageConverter.setObjectMapper(new JacksonObjectMapper());
        // 3. 将转换器对象添加到 mvc 框架的转换器集合中（靠前的位置）
        converters.add(0,messageConverter);
    }
}
